package com.mercury.ec.framework.air.core.client.impl;

import com.mercury.ec.framework.air.core.client.AirClient;
import com.mercury.ec.framework.air.core.client.AirClientFactory;
import com.mercury.ec.framework.air.core.client.impl.qunar.QuanrAirClient;
import com.mercury.ec.framework.air.core.client.impl.skyecho.SkyechoAirClient;
import com.mercury.ec.framework.air.core.client.impl.sunstn.SunstnAirClient;
import com.mercury.ec.framework.air.core.property.AirChannelProperties;
import com.mercury.ec.module.basic.enums.BasicAirChannelTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 机票客户端工厂接口
 *
 * @author hesx
 */
@Validated
@Slf4j
public class AirClientFactoryImpl implements AirClientFactory {

    /**
     * 机票客户端 Map
     * key：渠道编号，使用 {@link AirChannelProperties#getId()}
     */
    private final ConcurrentMap<Long, AbstractAirClient> channelIdClients = new ConcurrentHashMap<>();

    @Override
    public AirClient getAirClient(Long channelId) {
        return channelIdClients.get(channelId);
    }

    @Override
    public void createOrUpdateAirClient(AirChannelProperties properties) {
        AbstractAirClient client = channelIdClients.get(properties.getId());
        if (client == null) {
            client = this.createAirClient(properties);
            if (client != null) {
                client.init();
                channelIdClients.put(client.getId(), client);
            }
        } else {
            client.refresh(properties);
        }
    }

    private AbstractAirClient createAirClient(AirChannelProperties properties) {
        BasicAirChannelTypeEnum channelEnum = BasicAirChannelTypeEnum.getByType(properties.getChannelType());
        Assert.notNull(channelEnum, String.format("渠道类型(%s) 为空", channelEnum));
        // 创建客户端
        switch (channelEnum) {
            case QUNAR:
                return new QuanrAirClient(properties);
            case SHOPPING:
                return new SkyechoAirClient(properties);
            case BSP:
                return new SunstnAirClient(properties);
        }
        // 创建失败，错误日志 + 抛出异常
//        log.error("[createAirClient][配置({}) 找不到合适的客户端实现]", properties);
//        throw new IllegalArgumentException(String.format("配置(%s) 找不到合适的客户端实现", properties));
        return new SkyechoAirClient(properties);// toto 待优化
    }
}